<template>
  <div class="interrogation-order">
    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><Grid /></el-icon>
          <span>筛选</span>
        </div>
      </template>

      <el-form :model="filterForm" inline>
        <el-form-item label="患者信息">
          <el-input
            v-model="filterForm.keyword"
            placeholder="输入患者姓名或手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="问诊方式">
          <el-select
            v-model="filterForm.consultationMethod"
            placeholder="请选择..."
            clearable
            style="width: 150px"
          >
            <el-option label="视频问诊" :value="0" />
            <el-option label="电话问诊" :value="5" />
            <el-option label="图文问诊" :value="10" />
          </el-select>
        </el-form-item>

        <el-form-item label="问诊来源">
          <el-select
            v-model="filterForm.consultationSource"
            placeholder="请选择..."
            clearable
            style="width: 150px"
          >
            <el-option label="线上问诊" :value="0" />
            <el-option label="线下问诊" :value="5" />
            <el-option label="转诊问诊" :value="10" />
          </el-select>
        </el-form-item>

        <el-form-item label="日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区域 -->
    <el-card class="data-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><List /></el-icon>
          <span>数据列表</span>
        </div>
      </template>

      <!-- 状态标签 -->
      <el-tabs
        v-model="activeStatus"
        @tab-change="handleStatusChange"
        class="status-tabs"
      >
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="待支付" name="pending" />
        <el-tab-pane label="进行中" name="in-progress" />
        <el-tab-pane label="已完成" name="completed" />
        <el-tab-pane label="已取消" name="cancelled" />
        <el-tab-pane label="已退诊" name="refunded" />
      </el-tabs>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        :loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="createTime" label="提交问诊时间" min-width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="patientName" label="患者" min-width="120" />
        <el-table-column prop="department" label="科室" min-width="100" />
        <el-table-column prop="doctor" label="医生" min-width="100" />
        <el-table-column prop="consultationMethodName" label="方式" width="100">
          <template #default="scope">
            <el-tag
              :type="getConsultationMethodType(scope.row.consultationMethod)"
            >
              {{ scope.row.consultationMethodName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="consultationSourceName" label="来源" width="100">
          <template #default="scope">
            <el-tag
              :type="getConsultationSourceType(scope.row.consultationSource)"
            >
              {{ scope.row.consultationSourceName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="consultationFee"
          label="问诊费"
          width="100"
          align="right"
        >
          <template #default="scope">
            ¥{{ scope.row.consultationFee?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
              {{ getOrderStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Grid, List, Search } from "@element-plus/icons-vue";
import { OrderAPI } from "../api/order";

// 路由相关
const router = useRouter();

// 响应式数据
const loading = ref(false);
const activeStatus = ref("all");
const selectedRows = ref<any[]>([]);

// 筛选表单
const filterForm = reactive({
  keyword: "",
  consultationMethod: undefined,
  consultationSource: undefined,
  dateRange: [],
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

// 表格数据
const tableData = ref([]);

// 问诊方式枚举
const ConsultationMethod = {
  VIDEO: 0, // 视频问诊
  PHONE: 5, // 电话问诊
  TEXT: 10, // 图文问诊
};

// 问诊来源枚举
const ConsultationSource = {
  ONLINE: 0, // 线上问诊
  OFFLINE: 5, // 线下问诊
  REFERRAL: 10, // 转诊问诊
};

// 订单状态枚举
const OrderStatus = {
  PENDING: 0, // 待支付
  IN_PROGRESS: 5, // 进行中
  COMPLETED: 10, // 已完成
  CANCELLED: 15, // 已取消
  REFUNDED: 20, // 已退诊
};

// 计算当前选中的状态值
const currentOrderStatus = computed(() => {
  switch (activeStatus.value) {
    case "pending":
      return OrderStatus.PENDING; // 0
    case "in-progress":
      return OrderStatus.IN_PROGRESS; // 5
    case "completed":
      return OrderStatus.COMPLETED; // 10
    case "cancelled":
      return OrderStatus.CANCELLED; // 15
    case "refunded":
      return OrderStatus.REFUNDED; // 20
    default:
      return undefined; // 全部状态
  }
});

// 获取问诊方式类型
const getConsultationMethodType = (method: number) => {
  const methodMap: Record<number, string> = {
    [ConsultationMethod.VIDEO]: "primary",
    [ConsultationMethod.PHONE]: "success",
    [ConsultationMethod.TEXT]: "warning",
  };
  return methodMap[method] || "info";
};

// 获取问诊方式文本
const getConsultationMethodText = (method: number) => {
  const methodMap: Record<number, string> = {
    [ConsultationMethod.VIDEO]: "视频问诊",
    [ConsultationMethod.PHONE]: "电话问诊",
    [ConsultationMethod.TEXT]: "图文问诊",
  };
  return methodMap[method] || "未知";
};

// 获取问诊来源类型
const getConsultationSourceType = (source: number) => {
  const sourceMap: Record<number, string> = {
    [ConsultationSource.ONLINE]: "primary",
    [ConsultationSource.OFFLINE]: "success",
    [ConsultationSource.REFERRAL]: "warning",
  };
  return sourceMap[source] || "info";
};

// 获取问诊来源文本
const getConsultationSourceText = (source: number) => {
  const sourceMap: Record<number, string> = {
    [ConsultationSource.ONLINE]: "线上问诊",
    [ConsultationSource.OFFLINE]: "线下问诊",
    [ConsultationSource.REFERRAL]: "转诊问诊",
  };
  return sourceMap[source] || "未知";
};

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    [OrderStatus.PENDING]: "warning",
    [OrderStatus.IN_PROGRESS]: "primary",
    [OrderStatus.COMPLETED]: "success",
    [OrderStatus.CANCELLED]: "info",
    [OrderStatus.REFUNDED]: "danger",
  };
  return statusMap[status] || "info";
};

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    [OrderStatus.PENDING]: "待支付",
    [OrderStatus.IN_PROGRESS]: "进行中",
    [OrderStatus.COMPLETED]: "已完成",
    [OrderStatus.CANCELLED]: "已取消",
    [OrderStatus.REFUNDED]: "已退诊",
  };
  return statusMap[status] || "未知";
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 加载问诊订单数据
const loadInterrogationOrders = async () => {
  try {
    loading.value = true;

    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      Keyword: filterForm.keyword || undefined,
      StartTime: filterForm.dateRange?.[0] || undefined,
      EndTime: filterForm.dateRange?.[1] || undefined,
      ConsultationMethod: filterForm.consultationMethod,
      ConsultationSource: filterForm.consultationSource,
      OrderStatus: currentOrderStatus.value,
    };

    console.log("调用问诊订单API，参数:", params);
    console.log("当前选中状态:", activeStatus.value);
    console.log("计算的状态值:", currentOrderStatus.value);

    const response = await OrderAPI.getInterrogationOrdersPage(params);

    if (response && response.data) {
      tableData.value = response.data.data || [];
      pagination.total = response.data.totalCount || 0;
      console.log("问诊订单数据加载成功:", response);
      console.log("加载到", tableData.value.length, "条数据");
    } else {
      console.error("API响应格式错误:", response);
      ElMessage.error("数据加载失败");
    }
  } catch (error) {
    console.error("加载问诊订单数据失败:", error);
    ElMessage.error("数据加载失败，请检查网络连接");
  } finally {
    loading.value = false;
  }
};

// 处理筛选
const handleFilter = () => {
  console.log("筛选按钮点击，当前筛选条件:", {
    keyword: filterForm.keyword,
    consultationMethod: filterForm.consultationMethod,
    consultationSource: filterForm.consultationSource,
    dateRange: filterForm.dateRange,
    activeStatus: activeStatus.value,
  });
  pagination.currentPage = 1;
  loadInterrogationOrders();
};

// 处理状态变化
const handleStatusChange = (tab: any) => {
  console.log("状态标签切换:", tab.props.label, "状态值:", activeStatus.value);

  // 直接计算状态值，避免反应慢一步的问题
  let orderStatus: number | undefined;
  switch (tab.props.name) {
    case "pending":
      orderStatus = OrderStatus.PENDING; // 0
      break;
    case "in-progress":
      orderStatus = OrderStatus.IN_PROGRESS; // 5
      break;
    case "completed":
      orderStatus = OrderStatus.COMPLETED; // 10
      break;
    case "cancelled":
      orderStatus = OrderStatus.CANCELLED; // 15
      break;
    case "refunded":
      orderStatus = OrderStatus.REFUNDED; // 20
      break;
    default:
      orderStatus = undefined; // 全部状态
  }

  console.log("直接计算的状态值:", orderStatus);

  pagination.currentPage = 1;

  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    // 临时覆盖loadInterrogationOrders中的状态值
    const tempLoadInterrogationOrders = async () => {
      try {
        loading.value = true;

        const params = {
          PageIndex: pagination.currentPage,
          PageSize: pagination.pageSize,
          Keyword: filterForm.keyword || undefined,
          StartTime: filterForm.dateRange?.[0] || undefined,
          EndTime: filterForm.dateRange?.[1] || undefined,
          ConsultationMethod: filterForm.consultationMethod,
          ConsultationSource: filterForm.consultationSource,
          OrderStatus: orderStatus, // 使用直接计算的值
        };

        console.log("调用问诊订单API，参数:", params);
        console.log("当前选中状态:", activeStatus.value);
        console.log("直接计算的状态值:", orderStatus);

        const response = await OrderAPI.getInterrogationOrdersPage(params);

        if (response && response.data) {
          tableData.value = response.data.data || [];
          pagination.total = response.data.totalCount || 0;
          console.log("问诊订单数据加载成功:", response);
          console.log("加载到", tableData.value.length, "条数据");
        } else {
          console.error("API响应格式错误:", response);
          ElMessage.error("数据加载失败");
        }
      } catch (error) {
        console.error("加载问诊订单数据失败:", error);
        ElMessage.error("数据加载失败，请检查网络连接");
      } finally {
        loading.value = false;
      }
    };

    tempLoadInterrogationOrders();
  });
};

// 处理查看
const handleView = (row: any) => {
  console.log("查看问诊订单:", row.orderNo);
  router.push(`/orders/interrogation-detail/${row.id}`);
};

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
  console.log("选中的行:", selectedRows.value);
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadInterrogationOrders();
};

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadInterrogationOrders();
};

// 页面加载时获取数据
onMounted(() => {
  loadInterrogationOrders();
});
</script>

<style scoped>
.interrogation-order {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-card,
.data-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.status-tabs {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-table {
  margin-top: 15px;
}
</style>